package com.young.mhl.service;

import com.young.mhl.dao.BillDAO;
import com.young.mhl.dao.MultiTableDAO;
import com.young.mhl.domain.Bill;
import com.young.mhl.domain.MultiTableBean;

import java.util.List;
import java.util.UUID;

/**
 * @Author: young
 * @Date: 2021-12-04 17:28
 * @Description:
 */
public class BillService {
	private BillDAO billDAO = new BillDAO();
	//定义MenuService属性
	private MenuService menuService = new MenuService();
	//定义DiningTableService属性
	private DiningTableService diningTableService = new DiningTableService();
	//
	private MultiTableDAO multiTableDAO = new MultiTableDAO();
	
	// 编写点餐，生成账单，更新对应餐桌状态
	public boolean orderMenu(int menuId, int nums, int diningTableId) {
		// 生成账单号，UUID
		String billId = UUID.randomUUID().toString();
		
		// 将账单生成到bill表
		int update = billDAO.update("insert into bill values(null,?,?,?,?,?,now(),'未结账')", billId, menuId, nums, menuService.getMenuById(menuId).getPrice() * nums, diningTableId);
		if (update <= 0) {
			return false;
		}
		
		//需要更新对应餐桌的状态
		return diningTableService.updateDiningTableState(diningTableId, "就餐中");
	}
	
	//返回账单信息
	public List<Bill> list() {
		return billDAO.queryMany("select * from bill", Bill.class);
	}
	//用多表查询返回账单信息和菜品名
	public List<MultiTableBean> list2() {
		return multiTableDAO.queryMany("select bill.*,name,price from bill,menu where bill.menuId=menu.id",MultiTableBean.class);
	}
	
	// 查看某个餐桌是否有未结账
	public boolean hasPayBillByDiningTableId(int diningTableId) {
		Bill bill = billDAO.querySingle("select * from bill where diningTableId=? and state='未结账' limit 0,1", Bill.class, diningTableId);
		return bill != null;
	}
	
	// 完成结账
	public boolean payBill(int diningTableId, String payMode) {
		//修改bill表
		int update = billDAO.update("update bill set state=? where diningTableId=? and state='未结账'", payMode, diningTableId);
		if (update <= 0) {
			return false;
		}
		// 修改diningTable
		if (!diningTableService.updateDiningTableStateToFree(diningTableId, "空")) {
			return false;
		}
		return true;
	}

}